package com.apes.crm.vip.base;

import com.apes.framework.api.DomainService;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 功能：会员级别 Service
 *
 * @author HuJianlin
 * @create 2018-03-15 14:35
 */
@Service("vipLevelService")
public class VipLevelService extends DomainService {

    @Autowired
    VipLevelRepository vipLevelRepository;

    public VipLevel save(SimpleRequest request) {
        VipLevel vipLevel = request.getO(VipLevel.class);
        return vipLevelRepository.saveAndFlush(vipLevel);
    }

    public VipLevel update(SimpleRequest request) {
        String id = request.get("id");
        int version = request.get("version");

        // 从数据库中取数，检查数据
        VipLevel oldVipLevel = vipLevelRepository.findOne(id);
        if (oldVipLevel == null) throw new RuntimeException("会员级别【" + id + "】在系统中不存在。");
        if (oldVipLevel.getVersion() != version) throw new RuntimeException("记录已更新或已删除，请重新提交！");

        VipLevel vipLevel = request.getO(VipLevel.class);
        return vipLevelRepository.saveAndFlush(vipLevel);
    }

    public List<VipLevel> findAll(SimpleRequest request) {
        return vipLevelRepository.findAll();
    }

    public Page<VipLevel> find(SimpleRequest request) {
        return vipLevelRepository.find(request.get("key"), PageRequest.of(request.get("page"), request.get("size")));
    }
}
